package com.example.game_app.fragment;

import android.app.AlertDialog;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.game_app.R;
import com.example.game_app.adapter.StrategyListAdapter;
import com.example.game_app.util.Request;
import com.example.game_app.util.UserContext;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;

public class GameStrategyViewFragment extends Fragment {
    // 攻略列表视图
    ListView listView;
    // 攻略元素集合
    List<Map<String, String>> strategyList = new ArrayList<>();
    private Handler mHandler = new Handler(Looper.getMainLooper());

    String gameName = "0";

    // 点击添加按钮
    LinearLayout addLayout;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局文件并返回视图
        return inflater.inflate(R.layout.game_strategy_view, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 在这里初始化视图和设置监听器等操作
        listView = view.findViewById(R.id.strategyLists);
        // bundle判断是否是从游戏列表跳转
        if (getArguments() != null) {
            gameName = getArguments().getString("GameName");
            getArguments().putString("GameName", "0");
        }
        if ("0".equals(gameName)) {
            getStrategyList();
        } else {
            GetStrategyByGameName(gameName);
            gameName = "0";
        }

        // 添加攻略 -- 点击事件
        addLayout = view.findViewById(R.id.addStrategyButton);
        addLayout.setOnClickListener(v -> showAddStrategyDialog());
    }

    // 显示 新增策略 弹出框
    private void showAddStrategyDialog() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
        final EditText etStrategyName = new EditText(getContext());
        etStrategyName.setHint("攻略名称");
        final EditText etStrategyContent = new EditText(getContext());
        etStrategyContent.setHint("攻略内容");
        final EditText etStrategyTag = new EditText(getContext());
        etStrategyTag.setHint("攻略分类（游戏名）");
        alertDialogBuilder.setView(new LinearLayout(getContext()) {{
                    setOrientation(LinearLayout.VERTICAL);
                    addView(etStrategyName);
                    addView(etStrategyContent);
                    addView(etStrategyTag);
                }})
                .setTitle("添加攻略")
                .setPositiveButton("确定", (dialog, which) -> {
                    String strategyName = etStrategyName.getText().toString().trim();
                    String strategyContent = etStrategyContent.getText().toString().trim();
                    String strategyTag = etStrategyTag.getText().toString().trim();
                    // 调用添加策略的方法，传入用户输入的值
                    addNewStrategy(strategyName, strategyContent, strategyTag);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    // 添加攻略 方法
    private void addNewStrategy(String strategyName, String strategyContent, String strategyTag) {
        Map<String, String> map = new HashMap<>();
        map.put("strategyName", strategyName);
        map.put("strategyContent", strategyContent);
        map.put("strategyTag", strategyTag);

        strategyList.add(0, map); // 添加到列表顶部
        listView.post(() -> {
            // 确保getStrategyList()方法在线程完成后执行
            final CountDownLatch latch = new CountDownLatch(1);
            // 发起网络请求并处理响应
            new Thread(() -> {
                String accountId = UserContext.getUser(requireContext());
                String strategyId = Request.post("/strategies/add", "strategyName=" + strategyName +
                        "&strategyContent=" + strategyContent +
                        "&gameName=" + strategyTag +
                        "&accountId=" + accountId);
                if ("保存失败".equals(strategyId)) {
                    Log.e("add", "添加失败");
                    requireActivity().runOnUiThread(() -> Toast.makeText(GameStrategyViewFragment.this.getContext(), "新增策略失败", Toast.LENGTH_SHORT).show());
                } else {
                    UserContext.setStrategy(requireContext(), strategyId);
                    // 只有在添加成功后才更新UI,并给列表元素添加点击事件
                    mHandler.post(() -> {
                        listView.setAdapter(new StrategyListAdapter(requireContext(), strategyList, this::showDialog)); // 创建弹出框
                    });
                }
                // 无论成功还是失败，都执行countDown
                latch.countDown();
            }).start();
            try {
                latch.await(); // 这里会阻塞，直到countDown被调用
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                Log.e("Error", "Thread interrupted while waiting", e);
            }
            // 刷新攻略列表
            getStrategyList();
        });
    }



    /**
     * 获取所有攻略列表
     */
    private void getStrategyList() {
        new Thread() {
            @Override
            public void run() {
                Request request = new Request();
                String result = request.get("/strategies/list");
                // 数据转换并映射
                getJsonArray(result, strategyList);
            }
        }.start();
    }

    /**
     * 将 攻略列表 转化为 map
     *
     * @param result
     * @param strategyList
     */
    private void getJsonArray(String result, List<Map<String, String>> strategyList) {
        try {
            JSONArray jsonArray = new JSONArray(result);
            // 保证每次访问，情况列表，避免冗余添加
            strategyList.clear();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String strategyId = String.valueOf(jsonObject.getInt("strategyId"));
                String strategyName = jsonObject.getString("strategyName");
                String strategyContent = jsonObject.getString("strategyContent");
                String gameName = jsonObject.getString("gameName");

                Map<String, String> strategyMap = new HashMap<>();
                strategyMap.put("strategyId", strategyId);
                strategyMap.put("strategyName", strategyName);
                strategyMap.put("strategyContent", strategyContent);
                strategyMap.put("gameName", "[" + gameName + "]");
                strategyList.add(strategyMap);
            }
            // 适配器映射数据
            mHandler.post(() ->
                    listView.setAdapter(new StrategyListAdapter(requireContext(), strategyList, this::showDialog))); // 创建弹出框
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据 游戏名 获取攻略列表
     *
     * @param GameName
     */
    public void GetStrategyByGameName(String GameName) {
        new Thread() {
            @Override
            public void run() {
                String result = Request.post("/strategies/like", "gameName=" + GameName);
                // 数据转换并映射
                getJsonArray(result, strategyList);

            }
        }.start();

    }

    private void showDialog(Map<String, String> map1) {
        // 创建弹出框
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(listView.getContext());
        TextView messageView = new TextView(listView.getContext());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            messageView.setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Body1);
        }
        String message = "   标题:" + map1.get("strategyName") + "\n" +
                "   内容:" + map1.get("strategyContent");
        messageView.setText(message);
        alertDialogBuilder.setView(messageView)
                .setTitle("攻略详情")
                .setPositiveButton("确定", null)
                .create()
                .show();
    }

}
